package com.map.service;
import com.map.domain.BaseUrl;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.*;

public class socketCommunication {

	private void send(int command,int length, List<String> content){
		byte cm= (byte)(command);
		byte l= (byte)(length);
		byte [] head = new byte[2];
		head[0]=cm;
		head[1]=l;
		StringBuilder st= new StringBuilder();
		//System.out.println("Content size:"+content.size());
		for(int i=0;i<content.size();i++)
		{
		
			st.append(content.get(i)+"\n");
		}
		//System.out.println("Content is now:"+st.toString());
		try {
			Socket clientSocket = new Socket("localhost",31039);
			DataOutputStream out= new DataOutputStream(clientSocket.getOutputStream());
			out.write(head);
			out.writeBytes(st.toString());
			out.close();
			clientSocket.close();
		} catch (IOException e) {
			System.out.println("There is an IO exception");
			e.printStackTrace();
		}
		
		
	}
	public void sendUrl(BaseUrl baseurl) {
		//System.out.println("see sent url" + baseurl.getNumUrl()+" "+baseurl.getBaseurl());
		//baseurl.setNumUrl(baseurl.getNumfromBaseUrl(baseurl.getBaseurl()));
		send(0,baseurl.getNumUrl(),baseurl.getUrlList());
		//System.out.println("restart " + baseurl.getNumUrl()+baseurl.getBaseurl());
	}
	
	public void stop() {
		send(2,0,new ArrayList<String>());
		System.out.println("stop");
	}
	
	public void save(String filename) {
		List<String> temp = new ArrayList<String>();
		temp.add(filename);
	   send(3,1,temp);	
	   System.out.println("save "+filename);
	}
    public void resume() {
    	send(1,0,new ArrayList<String>());
    	System.out.println("resume from last session");
    }
}
